package com.maotai.app.thread;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.client.config.RequestConfig;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.maotai.app.bean.MaotaiAppCookie;
import com.maotai.app.bean.MaotaiAppString;
import com.maotai.app.service.MaotaiAppService;
import com.maotai.app.util.MaotaiAppHttpClientUtil;
import com.maotai.llzhou.bean.CustomName;
import com.maotai.llzhou.util.IPFactory;

public class MaoTaiAppInfoCheckThreadNew extends Thread {
	private MaotaiAppService maotaiAppService;
	private Map<String, Object> zhanghao;
	private String ipAndPort;
	private Map<String, Object> shopMap;


	public MaoTaiAppInfoCheckThreadNew(MaotaiAppService maotaiAppService,
			Map<String, Object> zhanghao, String ipAndPort,
			Map<String, Object> shopMap) {
		super();
		this.maotaiAppService = maotaiAppService;
		this.zhanghao = zhanghao;
		this.ipAndPort = ipAndPort;
		this.shopMap = shopMap;
	}

	public Map<String, Object> getShopMap() {
		return shopMap;
	}

	public void setShopMap(Map<String, Object> shopMap) {
		this.shopMap = shopMap;
	}

	public String getIpAndPort() {
		return ipAndPort;
	}

	public void setIpAndPort(String ipAndPort) {
		this.ipAndPort = ipAndPort;
	}

	public Map<String, Object> getZhanghao() {
		return zhanghao;
	}

	public void setZhanghao(Map<String, Object> zhanghao) {
		this.zhanghao = zhanghao;
	}

	public MaotaiAppService getMaotaiAppService() {
		return maotaiAppService;
	}

	public void setMaotaiAppService(MaotaiAppService maotaiAppService) {
		this.maotaiAppService = maotaiAppService;
	}

	@Override
	public void run() {
		if (zhanghao.get("auth") == null || "".equals(zhanghao.get("auth"))) {
			// 先执行登录操作
			return;
		}
		try {
			MaotaiAppHttpClientUtil hcu = MaotaiAppHttpClientUtil.getInstance();
			
			RequestConfig config = IPFactory.getKdRequestConfig(ipAndPort);

			String acwTc = zhanghao.get("acwTc") + "";
			String auth = zhanghao.get("auth") + "";
			String memberid = zhanghao.get("memberid") + "";
			String invoiceId = zhanghao.get("invoiceId") + "";
			Map<String, Object> personName = maotaiAppService.getPersonName();
			String name = personName.get("name") + "";// 加上一个随机字母
			// 访问注册地址
			MaotaiAppCookie mc = new MaotaiAppCookie();
			mc.setAcwTc(acwTc);
			mc.setAuth(auth);
			mc.setMemberid(memberid);
			
			// 如果userId为空，那么需要修改数据库的userId
			if (invoiceId == null || "".equals(invoiceId)
					|| "null".equals(invoiceId)) {
				// 查询发票
				mc = hcu.sendHttpGetProxy(MaotaiAppString.INVOICE_QUERY_URL_NEW,
						mc, config, null);
				System.out.println(zhanghao.get("code") + " 查询得发票信息："
						+ mc.getContent());
				// {"data":[{"isSupport":null,"list":[{"accountId":3586409,"bankAccount":"","contactAddress":null,"contactPerson":null,"contactPhone":null,"createPerson":"migration program","createTime":"2017-12-11 16:39:05","def1":null,"def10":null,"def11":null,"def12":null,"def13":null,"def14":null,"def15":null,"def16":null,"def17":null,"def18":null,"def19":null,"def2":null,"def20":null,"def21":null,"def22":null,"def23":null,"def24":null,"def25":null,"def3":null,"def4":null,"def5":null,"def6":null,"def7":null,"def8":null,"def9":null,"dr":0,"id":461141,"invoiceContent":null,"invoiceContentType":1,"invoiceTaxType":1,"invoiceTitle":"鍛ㄤ寒浜?,"invoiceTitleType":1,"invoiceType":0,"isDefault":2,"openBank":"","orderBy":null,"orderByDesc":null,"orgName":"鍛ㄤ寒浜?,"registerAddress":"","registerPhone":"","sendType":null,"sqlFilters":null,"taxCode":"","tenantId":1,"updatePerson":"migration program","updateTime":"2018-06-24 14:31:07"}],"memberId":3586409,"shopId":null,"shopInvoice":null,"sign":null}],"resultCode":0,"resultMsg":"success"}
				if (mc.getContent() != null && !"".equals(mc.getContent())) {
					JSONObject jObject2 = JSONObject.parseObject(mc
							.getContent());
					JSONArray data2 = jObject2.getJSONArray("data");
					JSONArray data3 =((JSONObject) data2
							.get(0)).getJSONArray("list");
					
					if (data3 == null || data3.size() == 0) {
						System.out.println("账号没有发票信息--");
						// 新增发票信息
						if (addInvoiceId(maotaiAppService, zhanghao, hcu, mc,
								config, name)) {
							System.out.println(zhanghao.get("code")
									+ "---新增发票成功");
						}
					} else {
						// 新增功能，把发票id同步到数据库
						for (int i = 0; i < data3.size(); i++) {
							JSONObject obj = data3.getJSONObject(i);
							String accountId = obj.getString("accountId");
							invoiceId = obj.getString("id");
							String invoiceTitle = obj.getString("invoiceTitle");
							String orgName = obj.getString("orgName");
							String createPerson = obj.getString("createPerson");
							String createTime = obj.getString("createTime");
							String updatePerson = obj.getString("updatePerson");
							String updateTime = obj.getString("updateTime");
							String invoiceContent = obj.getString("invoiceContent");
							String invoicetext = obj.toString();
							String isDefault = obj.getString("isDefault");
							zhanghao.put("invoiceId", invoiceId);
							zhanghao.put("accountId", accountId);
							zhanghao.put("id", invoiceId);
							zhanghao.put("invoiceTitle", invoiceTitle);
							zhanghao.put("orgName", orgName);
							zhanghao.put("createPerson", createPerson);
							zhanghao.put("createTime", createTime);
							zhanghao.put("updatePerson", updatePerson);
							zhanghao.put("updateTime", updateTime);
							zhanghao.put("invoicetext", invoicetext);
							zhanghao.put("invoiceContent", invoiceContent);
							zhanghao.put("invoiceId", invoiceId);
							zhanghao.put("isDefault", isDefault);
							if(memberid == null || "".equals(memberid)|| "null".equals(memberid)){
								memberid = data2.getJSONObject(0).getString("memberId");
								zhanghao.put("memberid", memberid);
								maotaiAppService.updateMaotaiMemberId(zhanghao);
							}
							maotaiAppService.updateMaotaiInvoiceId(zhanghao);
							maotaiAppService.insertMaotaiInvoice(zhanghao);
						}
					}
				} 
			}
			// 增加地址
		// 查询地址
		mc = hcu.sendHttpGetProxy(MaotaiAppString.ADDRESS_QUERY_URL_NEW, mc,
				config, null);
		// {"data":[{"accountId":3586409,"address":"天禄大道1号翠屏城73栋805室","addressAlias":"","areaCode":"320115000000","areaName":"江宁区","cityCode":"320100000000","cityName":"南京市","createPerson":"nickboowen","createTime":"2018-06-27 10:17:38","def1":null,"def10":null,"def11":null,"def12":null,"def13":null,"def14":null,"def15":null,"def16":null,"def17":null,"def18":null,"def19":null,"def2":null,"def20":null,"def21":null,"def22":null,"def23":null,"def24":null,"def25":null,"def3":null,"def4":null,"def5":null,"def6":null,"def7":null,"def8":null,"def9":null,"defaultStatus":1,"deliveryEmail":"","deliveryMobile":"13372007847","deliveryName":"周亮亮","deliveryPhone":null,"dr":0,"id":"1179370534174015495","latitude":null,"longitude":null,"orderBy":null,"orderByDesc":null,"postcode":null,"provinceCode":"320000000000","provinceName":"江苏省","sqlFilters":null,"streetCode":null,"streetName":"","tenantId":1,"updatePerson":"nickboowen","updateTime":"2018-06-27 10:17:38"}],"resultCode":0,"resultMsg":"success"}
		System.out.println(mc.getContent());
		if (mc.getContent() != null && !"".equals(mc.getContent())) {
			JSONObject jObject2 = JSONObject.parseObject(mc
					.getContent());
			JSONArray data2 = jObject2.getJSONArray("data");

			if (data2 == null || data2.size() == 0) {
			// 新增收货地址
				boolean isAdd = addAddress(maotaiAppService, zhanghao, hcu, mc,
						config, name);
				if (isAdd) {
					// 插入到地址表中
				} else {
//					zhanghao.put("checkstatus", "0");
//					maotaiAppService.updateMaotaiAppInfoCheckStatus(zhanghao);
				}
			} else {

				// 新增功能，把发票id同步到数据库
				if (data2 != null && data2.size() > 0) {
					for (int i = 0; i < data2.size(); i++) {
						JSONObject dataObject = data2.getJSONObject(i);
						String accountId = dataObject.getString("accountId");
						String address = dataObject.getString("address");
						String areaCode = dataObject.getString("areaCode");
						String areaName = dataObject.getString("areaName");
						String cityCode = dataObject.getString("cityCode");
						String cityName = dataObject.getString("cityName");
						String provinceCode = dataObject
								.getString("provinceCode");
						String provinceName = dataObject
								.getString("provinceName");
						String createPerson = dataObject
								.getString("createPerson");
						String createTime = dataObject.getString("createTime");
						String deliveryMobile = dataObject
								.getString("deliveryMobile");
						String deliveryName = dataObject
								.getString("deliveryName");
						String id = dataObject.getString("id");
						String latitude = dataObject.getString("latitude");
						String longitude = dataObject.getString("longitude");
						zhanghao.put("accountId", accountId);
						zhanghao.put("address", address);
						zhanghao.put("areaCode", areaCode);
						zhanghao.put("areaName", areaName);
						zhanghao.put("cityCode", cityCode);
						zhanghao.put("cityName", cityName);
						zhanghao.put("provinceCode", provinceCode);
						zhanghao.put("provinceName", provinceName);
						zhanghao.put("createPerson", createPerson);
						zhanghao.put("createTime", createTime);
						zhanghao.put("deliveryMobile", deliveryMobile);
						zhanghao.put("deliveryName", deliveryName);
						zhanghao.put("id", id);
						zhanghao.put("latitude", latitude);
						zhanghao.put("longitude", longitude);
						maotaiAppService.insertMaotaiAppAddress(zhanghao);
					}
				}
			}
		}
		} catch (Exception e) {
			e.printStackTrace();
			zhanghao.put("checkstatus", "0");
			try {
				maotaiAppService.updateMaotaiAppInfoCheckStatus(zhanghao);
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
	}
	private boolean addInvoiceId(MaotaiAppService maotaiService,
			Map<String, Object> zhanghao, MaotaiAppHttpClientUtil hcu,
			MaotaiAppCookie mwc, RequestConfig config, String name)
			throws Exception {
		// 新增发票
		Map<String, String> orderMap = new HashMap<String, String>();
		orderMap.put("invoiceTitleType", "1");
		orderMap.put("invoiceType", "2");
		orderMap.put("invoiceTaxType", "1");
		orderMap.put("invoiceTitle", name);
		orderMap.put("orgName", "");
		orderMap.put("invoiceContent", "明细");
		orderMap.put("taxCode", "");
		orderMap.put("openBank", "");
		orderMap.put("bankAccount", "");
		orderMap.put("registerAddress", "");
		orderMap.put("registerPhone", "");
		orderMap.put("isDefault", "1");
		mwc = hcu.sendHttpPostProxy(MaotaiAppString.INVOICE_ADD_URL_NEW, mwc,
				orderMap, config, null);
		// {"data":null,"resultCode":0,"resultMsg":"success"}
//		System.out.println(mwc.getContent());
//		if (mwc.getContent().contains("success")) {
			// 查询发票
			mwc = hcu.sendHttpGetProxy(MaotaiAppString.INVOICE_QUERY_URL_NEW, mwc,
					config, null);
			System.out.println(zhanghao.get("code") + " 查询得发票信息："
					+ mwc.getContent());
			// {"data":[{"isSupport":null,"list":[{"accountId":3586409,"bankAccount":"","contactAddress":null,"contactPerson":null,"contactPhone":null,"createPerson":"migration program","createTime":"2017-12-11 16:39:05","def1":null,"def10":null,"def11":null,"def12":null,"def13":null,"def14":null,"def15":null,"def16":null,"def17":null,"def18":null,"def19":null,"def2":null,"def20":null,"def21":null,"def22":null,"def23":null,"def24":null,"def25":null,"def3":null,"def4":null,"def5":null,"def6":null,"def7":null,"def8":null,"def9":null,"dr":0,"id":461141,"invoiceContent":null,"invoiceContentType":1,"invoiceTaxType":1,"invoiceTitle":"鍛ㄤ寒浜?,"invoiceTitleType":1,"invoiceType":0,"isDefault":2,"openBank":"","orderBy":null,"orderByDesc":null,"orgName":"鍛ㄤ寒浜?,"registerAddress":"","registerPhone":"","sendType":null,"sqlFilters":null,"taxCode":"","tenantId":1,"updatePerson":"migration program","updateTime":"2018-06-24 14:31:07"}],"memberId":3586409,"shopId":null,"shopInvoice":null,"sign":null}],"resultCode":0,"resultMsg":"success"}
			if (mwc.getContent() != null && !"".equals(mwc.getContent())) {
				JSONObject jObject2 = JSONObject.parseObject(mwc.getContent());
				JSONArray data2 = jObject2.getJSONArray("data");

				// 新增功能，把发票id同步到数据库
				JSONObject obj = (JSONObject) (((JSONObject) data2.get(0))
						.getJSONArray("list").get(0));
				String accountId = obj.getString("accountId");
				String invoiceId = obj.getString("id");
				String invoiceTitle = obj.getString("invoiceTitle");
				String orgName = obj.getString("orgName");
				String createPerson = obj.getString("createPerson");
				String createTime = obj.getString("createTime");
				String updatePerson = obj.getString("updatePerson");
				String updateTime = obj.getString("updateTime");
				String invoiceContent = obj.getString("invoiceContent");
				String invoicetext = obj.toString();
				zhanghao.put("invoiceId", invoiceId);
				zhanghao.put("accountId", accountId);
				zhanghao.put("id", invoiceId);
				zhanghao.put("invoiceTitle", invoiceTitle);
				zhanghao.put("orgName", orgName);
				zhanghao.put("createPerson", createPerson);
				zhanghao.put("createTime", createTime);
				zhanghao.put("updatePerson", updatePerson);
				zhanghao.put("updateTime", updateTime);
				zhanghao.put("invoicetext", invoicetext);
				zhanghao.put("invoiceContent", invoiceContent);
				String memberid = data2.getJSONObject(0).getString("memberId");
				zhanghao.put("memberid", memberid);
				maotaiAppService.updateMaotaiMemberId(zhanghao);
				maotaiAppService.updateMaotaiInvoiceId(zhanghao);
				maotaiAppService.insertMaotaiInvoice(zhanghao);
				return true;
			}
//		}
		return false;
	}

	private boolean addAddress(MaotaiAppService maotaiService,
			Map<String, Object> zhanghao, MaotaiAppHttpClientUtil hcu,
			MaotaiAppCookie mwc, RequestConfig config, String name)
			throws Exception {
		Map<String, String> addressMap = new HashMap<String, String>();
		String telphone = zhanghao.get("phone") + "";
		// 从数据库中获取省市区
//		Map<String, Object> countryMap = maotaiService.getCountryRandom();
//		Map<String, Object> countryMap = maotaiService.getCountryRandomMY();
		String provinceid = shopMap.get("provinceCode") + "";
//		String provincename = countryMap.get("provincename") + "";
		String cityid = shopMap.get("cityCode") + "";
//		String cityname = countryMap.get("cityname") + "";
		String areaid = shopMap.get("countyCode") + "";
//		String areaname = countryMap.get("areaname") + "";
		int lou = CustomName.getRandomGuiZe();
		String detailAddress = shopMap.get("detailAddress") +""+ CustomName.getAddressCode()+"号"+CustomName.getRandomGuiZe() + "栋"  + lou + "0"
				+ CustomName.getNum1() + "室";
		String lati = shopMap.get("latitude") + "";
		String longi = shopMap.get("longitude") + "";
//		addresss = addrObj.getString("address") + addressname;
		addressMap.put("deliveryName", name);
		addressMap.put("address", detailAddress);
		addressMap.put("deliveryMobile", telphone);
		addressMap.put("deliveryEmail", "");
		addressMap.put("addressAlias", "");
		addressMap.put("provinceCode", provinceid);
		addressMap.put("cityCode", cityid);
		addressMap.put("areaCode", areaid);
		addressMap.put("defaultStatus", "1");
		addressMap.put("latitude", lati);
		addressMap.put("longitude", longi);
		mwc = hcu.sendHttpPostProxy(MaotaiAppString.ADDRESS_ADD_URL_NEW, mwc,
				addressMap, config, null);
		// {"data":null,"resultCode":0,"resultMsg":"success"}
//		System.out.println(mwc.getContent());
//		if (mwc.getContent().contains("success")) {
			// 查询地址
			mwc = hcu.sendHttpGetProxy(MaotaiAppString.ADDRESS_QUERY_URL_NEW, mwc,
					config, null);
			System.out.println(zhanghao.get("code") + " 查询得地址信息："
					+ mwc.getContent());
			if (mwc.getContent() != null && !"".equals(mwc.getContent())) {
				JSONObject jObject2 = JSONObject.parseObject(mwc.getContent());
				JSONArray data2 = jObject2.getJSONArray("data");

				// 新增功能，把发票id同步到数据库
				if (data2 != null && data2.size() > 0) {
					for (int i = 0; i < data2.size(); i++) {
						JSONObject dataObject = data2.getJSONObject(i);
						String accountId = dataObject.getString("accountId");
						String address = dataObject.getString("address");
						String areaCode = dataObject.getString("areaCode");
						String areaName = dataObject.getString("areaName");
						String cityCode = dataObject.getString("cityCode");
						String cityName = dataObject.getString("cityName");
						String provinceCode = dataObject
								.getString("provinceCode");
						String provinceName = dataObject
								.getString("provinceName");
						String createPerson = dataObject
								.getString("createPerson");
						String createTime = dataObject.getString("createTime");
						String deliveryMobile = dataObject
								.getString("deliveryMobile");
						String deliveryName = dataObject
								.getString("deliveryName");
						String id = dataObject.getString("id");
						String latitude = dataObject.getString("latitude");
						String longitude = dataObject.getString("longitude");
						zhanghao.put("accountId", accountId);
						zhanghao.put("address", address);
						zhanghao.put("areaCode", areaCode);
						zhanghao.put("areaName", areaName);
						zhanghao.put("cityCode", cityCode);
						zhanghao.put("cityName", cityName);
						zhanghao.put("provinceCode", provinceCode);
						zhanghao.put("provinceName", provinceName);
						zhanghao.put("createPerson", createPerson);
						zhanghao.put("createTime", createTime);
						zhanghao.put("deliveryMobile", deliveryMobile);
						zhanghao.put("deliveryName", deliveryName);
						zhanghao.put("id", id);
						zhanghao.put("latitude", latitude);
						zhanghao.put("longitude", longitude);
						maotaiService.insertMaotaiAppAddress(zhanghao);
					}
				}
				return true;
			}
//		}
		return false;
	}
}
